package com.wl.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @program: treeHole
 * @author: 吴磊
 * @create: 2021-07-22 09:03
 */
@WebServlet("/upload.action")
public class UploadServlet2 extends HttpServlet {
    // D:\apache-tomcat-9.0.2\webapps\res_war_exploded\
    private File projectRootPathFile;
    private File webappsFile;
    private File picDirPath;
    private File saveDirPath;

    private String picDir = "respic";
    //   ../respic
    private String picWebUrl = ".." + File.separator + picDir;


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1、获取项目的根路径
        String projectRootPath = request.getServletContext().getRealPath("/");
        System.out.println("项目根路径projectRootPath:" + projectRootPath);
        //   ../respic/              File.separator  获取当前系统路径的分隔符
        projectRootPathFile = new File(projectRootPath);
        //3、所以webapps的路径为项目根路径的父路径
        webappsFile = projectRootPathFile.getParentFile();
        System.out.println("webapps的路径webappsFile:" + webappsFile);
        //所以图片的路径是webappsFile的picDir
        picDirPath = new File(webappsFile, picDir);
        System.out.println("pic目录的路径picDirPath:" + picDirPath);

        //存到respic下的按  yyyy/MM
        DateFormat df = new SimpleDateFormat("yyyy" + File.separator + "MM");
        String dir = df.format(new Date());
        saveDirPath = new File(picDirPath, dir);
        if (!saveDirPath.exists()) {
            saveDirPath.mkdirs();      //创建此目录
        }
        System.out.println("最终图片存在这个路径下saveDirPath;" + saveDirPath);  // **** D:\apache-tomcat-9.0.2\webapps\respic\2021\07
        String picUrl = picWebUrl + File.separator + dir;
        System.out.println("图片访问的url:" + picUrl);     // *****  ..\respic\2021\07


    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}